package org.lewis.demo.controller;

import org.lewis.demo.entity.SysUser;
import org.lewis.demo.repo.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequestMapping("register")
@RestController
public class RegisterController {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public RegisterController(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @PostMapping
    public void register(String username, String password, HttpServletResponse response) throws IOException {
        SysUser user = new SysUser(username, this.passwordEncoder.encode(password), true);
        this.userRepository.save(user);
        response.sendRedirect("/login");
    }

}
